//
//  OAuthViewController.swift
//  新浪微博
//
//  Created by macbook on 16/3/9.
//  Copyright © 2016年 buWangChuXing. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webview = UIWebView()
    //关闭按钮的实现
    @objc private func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func defaultAccount(){
        //需要在webView中 设置账号和密码
        let jsString = "document.getElementById('userId').value = '13022285567lei@sina.com', document.getElementById('passwd').value = 'buzhiduicuo'"
        //通过字符串来执行javascrip 代码
        webview.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    
    //将根视图替换成了webView
    override func loadView() {
        
        
        view = webview
        
        //设置代理  为蒙版
        webview.delegate = self
        
        //设置代理
        webview.delegate = self
        
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        //设置导航条
        
        setNavBar()
        //手动创建的视图控制器 根视图的背景 是 透明，所以得给他设置一个白色背景
        view.backgroundColor = UIColor.whiteColor()
        
        
        //加载授权页面
        loadOAuthPage()
    }
    //解决圈圈问题
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    //加载授权页面 用户需要输入用户名和密码  完成授权登陆
    private func loadOAuthPage() {
        
        //1.urlString
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=\(client_id)" + "&redirect_uri=\(redirect_uri)"
        //2.NSUrl
        let url = NSURL(string: urlString)
        
        //3. NSURLRequest
        let request = NSURLRequest(URL: url!)
        
        webview.loadRequest(request);
        
    }
    
    
    
    //设置导航控制器中关闭按钮
    private func setNavBar(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title:"关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "defaultAccount")
        
    }
}
//webView协议方法拿到扩展
extension OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    //一般协议方法 返回值 为 bool类型 默认返回yes  想对应的控件就能够正常工作 反之  不能正常工作
    //在这个协议方法中 可以监测到webView每次加载新的页面发起的网络请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL)
        //absoluteString表示URL的绝对路径
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        //包含了回调地址的url中一定包好了code字段
        //if xxxx.rangOfString .location != NSNotFound
        if urlString.containsString("code") {
            //不加载网页
            
            //在这个地方需要获取url中包好的code  使用code 获取token
            guard let query = request.URL?.query else {
                return false
            }
            
            let codeStr = "code="
            //将String 转换为NSString
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            //使用code 获取token
            loadAccessToken(code)
             //print(query,code)
            return false
        }
        
        return true
    }
    

    private func loadAccessToken(code: String) {
    
        let urlString = "https://api.weibo.com/oauth2/access_token"

        let parameters = ["client_id" : client_id,"client_secret" : client_secret,"grant_type" : "authorization_code","code" : code,"redirect_uri" : redirect_uri]
        
        
    let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        //发送post请求
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            print(result?.classForCoder)
            //获取token
            guard let dict = result as? [String : AnyObject] else {
            SVProgressHUD.showErrorWithStatus("数据格式错误")
            return
             }
            //标示用户访问接口  权限的一个时效性的标识
            self.loadUserInfo(dict)
            }) { (_,error ) -> Void in
                print(error)
        }
        
        
    }

    //获取用户信息 必须有俩数据access_token和uid，从上面就可以得到
    private func loadUserInfo(dict:[String : AnyObject]){
        
        let token = dict["access_token"] as! String
        //获取到用户接口访问权限之后，使用token获取用户信息
        let uid = dict["uid"] as!  String
        
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        //在字典中不能直接添加nil  可以添加空对象[NSNull null]
        let parameters = ["access_token" : token,"uid" : uid]
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //print(result)
            
            //接口返回的的数据确定为字典
            guard var userInforDict = result as?[String : AnyObject] else {
            
                SVProgressHUD.showErrorWithStatus("数据格式错误")
                return
            
            }
            print(userInforDict)
            //1.合并字典
            for(k,v) in dict {
            
                userInforDict[k] = v
            
            }
            //保存到沙盒
             UserAccount().saveUserInfo(userInforDict)
            
            }) { (_, error) -> Void in
                print(error)
        }
    
    }
    

}

